package com.company.project.web;

import com.company.project.application.dto.file.FileResult;
import com.company.project.config.file.fastdfs.FastDFSUtil;
import com.company.project.config.file.ftp.FtpFileUtil;
import com.company.project.core.Result;
import com.company.project.core.ResultGenerator;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.csource.common.MyException;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;

/**
 * =================================
 * <p>
 * Created by cjj on 18-9-1.
 * <p>
 * 描述: 文件上传接口
 */


@RestController
@RequestMapping("/file")
@Api(tags = "文件上传")
public class FileController {

    @RequestMapping(value = "/fastdfs/upload", method = RequestMethod.POST)
    @ApiOperation(value = "通过fastdfs上传文件", notes = "通过fastdfs上传文件的接口")
    public Result uploadFastdfs(MultipartFile file) {
        try {
            String oriName = file.getOriginalFilename();
            String upload = FastDFSUtil.upload(file);
            //获取文件上传成功后的名称
            String name = upload.substring(upload.lastIndexOf("/") + 1, upload.lastIndexOf("."));
            //返回文件的后缀名
            String pattern = upload.substring(upload.lastIndexOf(".") + 1);
            FileResult fileResult = new FileResult();
            fileResult.setName(oriName.substring(0, oriName.lastIndexOf(".")));
            fileResult.setUrl(upload);
            fileResult.setPattern(pattern);
            fileResult.setCreateDate(new Date());
            return ResultGenerator.genSuccessResult(fileResult);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (MyException e) {
            e.printStackTrace();
        }
        return ResultGenerator.genFailResult("文件上传异常");
    }

    @RequestMapping(value = "/local/project/upload", method = RequestMethod.POST)
    @ApiOperation(value = "本地文件上传，上传到项目目录下", notes = "本地文件上传的接口")
    public Result uploadLocalProject(MultipartFile file) {
        // 随机字符串，保证不重复
        String picName = UUID.randomUUID().toString();
        // 图片原始名字
        String oriName = file.getOriginalFilename();

        // 获取文件后缀名
        String extndName = oriName.substring(oriName.lastIndexOf("."));

        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String ip = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort();
        String filePath = request.getSession().getServletContext().getRealPath("file/");
        File newFile = new File(filePath);
        if (!newFile.exists()) {
            newFile.mkdirs();
        }
        try {
            System.out.println(filePath + picName + extndName);
            file.transferTo(new File(filePath + picName + extndName));
        } catch (IOException e) {
            e.printStackTrace();
            ResultGenerator.genFailResult("文件上传异常");
        }
        //从本地服务器打开
        String upload = ip + "/file/" + picName + extndName;
        FileResult fileResult = new FileResult();
        fileResult.setName(oriName.substring(0, oriName.lastIndexOf(".")));
        fileResult.setUrl(upload);
        fileResult.setPattern(extndName.substring(1));
        fileResult.setCreateDate(new Date());
        return ResultGenerator.genSuccessResult(fileResult);
    }

    @RequestMapping(value = "/local/system/upload", method = RequestMethod.POST)
    @ApiOperation(value = "本地文件上传，上传到服务器指定目录下", notes = "本地文件上传的接口")
    public Result uploadLocalSystem(MultipartFile file) {
        // 随机字符串，保证不重复
        String picName = UUID.randomUUID().toString();
        // 图片原始名字
        String oriName = file.getOriginalFilename();

        // 获取文件后缀名
        String extndName = oriName.substring(oriName.lastIndexOf("."));

        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String ip = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort();
        try {
            //文件的上传路径由配置文件里面决定
            file.transferTo(new File(picName + extndName));
        } catch (IOException e) {
            e.printStackTrace();
            ResultGenerator.genFailResult("文件上传异常");
        }
        //从上传的服务器打开
        String upload = ip + "/file/" + picName + extndName;
        FileResult fileResult = new FileResult();
        fileResult.setName(oriName.substring(0, oriName.lastIndexOf(".")));
        fileResult.setUrl(upload);
        fileResult.setPattern(extndName.substring(1));
        fileResult.setCreateDate(new Date());
        return ResultGenerator.genSuccessResult(fileResult);
    }

    //ftp处理文件上传
    @RequestMapping(value = "/ftp/upload", method = RequestMethod.POST)
    @ApiOperation(value = "上传文件到ftp服务器", notes = "上传文件到ftp服务器的接口")
    public Result uploadFtp(MultipartFile file) throws IOException {
        try {
            // 随机字符串，保证不重复
            String picName = UUID.randomUUID().toString();
            // 图片原始名字
            String oriName = file.getOriginalFilename();
            // 获取文件后缀名
            String extndName = oriName.substring(oriName.lastIndexOf("."));
            //上传ftp
            FtpFileUtil.uploadFile(picName, file.getInputStream());
            //得到可以访问的路径地址
            String upload = "http://" + FtpFileUtil.FTP_ADDRESS + ":" + FtpFileUtil.FTP_PORT
                    + FtpFileUtil.FTP_BASEPATH + picName + extndName;
            String pattern = extndName.substring(1);
            FileResult fileResult = new FileResult();
            fileResult.setName(oriName.substring(0, oriName.lastIndexOf(".")));
            fileResult.setUrl(upload);
            fileResult.setPattern(pattern);
            fileResult.setCreateDate(new Date());
            return ResultGenerator.genSuccessResult(fileResult);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ResultGenerator.genFailResult("文件上传异常");

    }

}
